//
//  RCSearchMoreTagsVC.m
//  RocketProject
//
//  Created by chen jiedan on 13-6-26.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCSearchMoreTagsVC.h"
#import "RCSearchAllCityDataModel.h"
#import "NSArray+EX.h"
#import "NSString+NSString_Ex_.h"
#import "RCSearchMoreCell.h"
#import "UIColor-Expanded.h"
#import "RCMerchantListVC.h"
#import "RCNearbyDiscountVC.h"

#define kLeftTableTag           101
#define kRightTableTag          102

#define kSignalImageFile               @"image_discount_signal.png"

@interface RCSearchMoreTagsVC ()

@property(nonatomic,retain) RCSearchAllCityDataModel *dataModel;
@property(nonatomic,retain) UITableView *leftTableView;
@property(nonatomic,retain) UITableView *rightTableView;
@property(nonatomic,assign) int64_t requestID;
@property(nonatomic,retain) MBProgressHUDEx *progressHub;
@property(nonatomic,assign) NSInteger currentSelectedCell;
@property(nonatomic,retain) NSMutableArray *selectItemArray;

@end

@implementation RCSearchMoreTagsVC

@synthesize dataModel = _dataModel;
@synthesize leftTableView = _leftTableView;
@synthesize rightTableView = _rightTableView;
@synthesize requestID = _requestID;
@synthesize progressHub = _progressHub;
@synthesize viewType = _viewType;
@synthesize cityID = _cityID;
@synthesize currentSelectedCell = _currentSelectedCell;
@synthesize selectItemArray = _selectItemArray;

@synthesize delegate = _delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

-(void)dealloc{
    [[IManager sharedInstance]cancelFetchDataRequestByRequestID:_requestID];
    self.delegate = nil;
    self.dataModel = nil;
    self.leftTableView.delegate = nil;
    self.leftTableView.dataSource = nil;
    self.leftTableView = nil;
    
    self.rightTableView.delegate = nil;
    self.rightTableView.dataSource = nil;
    self.rightTableView = nil;
    self.progressHub.delegate = nil;
    self.progressHub = nil;
    self.cityID = nil;
    self.selectItemArray = nil;
    [super dealloc];
}

-(id)initWithParameters:(NSString *)cityID WithType:(SearchMoreTagsVCType)viewType{
    self = [super init];
    if (self) {
        self.cityID = cityID;
        self.viewType = viewType;
        self.currentSelectedCell = 0;
    }
    return self;
}



-(void)loadView{
    [super loadView];
    if (_viewType == SearchMoreTagsVCTypeCategoryAndDiscount) {
        self.titleLabelText = @"最新优惠";
    }else if (_viewType == SearchMoreTagsVCTypeAddMerchant){
        self.titleLabelText = @"所有频道";
    }
    else{
        self.titleLabelText = @"搜全城";
    }
    self.navigationItem.titleView = [self createTitleView];
    
    NSArray *viewControllersArray = [self.navigationController viewControllers];
    if (viewControllersArray && [viewControllersArray count] <= 1){
        
        UIButton *signalButton = [UIButton buttonWithType:UIButtonTypeCustom];
        signalButton.frame = CGRectMake(0, 0, 44, 44);
        [signalButton setImage:[UIImage imageNamed:kSignalImageFile]
                      forState:UIControlStateNormal];
        [signalButton setImage:[UIImage imageNamed:kSignalImageFile]
                      forState:UIControlStateHighlighted];
        self.navigationItem.leftBarButtonItem = [self createLeftBarButtonItemWithButton:signalButton];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    CGFloat height = 0;
    if (_viewType == SearchMoreTagsVCTypeCategoryAndDiscount) {
        height = UIScreenHeight-64 -49;
    }else{
        height = UIScreenHeight-64;
    }
    if (!_leftTableView) {
        _leftTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 160, height) style:UITableViewStylePlain];
    }
    [NSTimer scheduledTimerWithTimeInterval:12 target:self selector:@selector(hideProgressHub) userInfo:nil repeats:NO];
    _leftTableView.backgroundColor = [UIColor whiteColor];
    _leftTableView.delegate = self;
    _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _leftTableView.dataSource = self;
    _leftTableView.tag = kLeftTableTag;
    [self.viewContainer addSubview:_leftTableView];
    
    
    if (!_rightTableView) {
        _rightTableView = [[UITableView alloc]initWithFrame:CGRectMake(160, 0, 160, height) style:UITableViewStylePlain];
    }
    _rightTableView.backgroundColor = [UIColor colorWithHex:0xfffcf5ef];
    _rightTableView.delegate = self;
    _rightTableView.dataSource = self;
    _rightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _rightTableView.tag = kRightTableTag;
    [self.viewContainer addSubview:_rightTableView];
    
    if (!_selectItemArray) {
        _selectItemArray = [[NSMutableArray alloc]initWithCapacity:1];
    }
    [self refreshData];
	// Do any additional setup after loading the view.
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[IManager sharedInstance]cancelFetchDataRequestByRequestID:_requestID];
}

-(void) refreshData
{
    _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                               TopHeight:0
                                        withBottomHeight:0
                                           withLeftWidth:0
                                          withRightWidth:0
                                    withExclusiveObjects:nil];
    _progressHub.delegate = self;
    _progressHub.labelText = @"加载中...";
    [self.view addSubview:_progressHub];
    [self.view bringSubviewToFront:_progressHub];
    [_progressHub show:YES];
    
    
    if (_viewType == SearchMoreTagsVCTypeCategory || _viewType == SearchMoreTagsVCTypeCategoryAndDiscount) {
        _requestID = [[IManager sharedInstance]requestSearchCityCategory:self.cityID withDelegate:self];
    }else{
        _requestID = [[IManager sharedInstance]requestSearchCityDistrict:self.cityID withDelegate:self];
    }
}

#pragma
#pragma mark IManage Delegate
-(void) updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId
{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        self.dataModel = (RCSearchAllCityDataModel *)dataModel;
        NSArray *valueArray = [self.dataModel.itemValueArray safeObjectAtIndex:self.currentSelectedCell];
        if (valueArray != nil) {
            [_selectItemArray removeAllObjects];
            [_selectItemArray addObjectsFromArray:valueArray];
        }
        
        [_leftTableView reloadData];
        [_rightTableView reloadData];
    }
    
    
    
}

-(void) updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId
{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
    }
    
}

-(void)hideProgressHub{
    [_progressHub removeFromSuperview];
    [_progressHub release];
    _progressHub = nil;
}

#pragma -mark UITableView

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == kLeftTableTag) {
        if (nil == self.dataModel && nil == self.dataModel.itemKeyArray) {
            return 0;
        }else{
            return [self.dataModel.itemKeyArray count];
        }
    }else if (tableView.tag == kRightTableTag){
        return [_selectItemArray count];
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == kLeftTableTag) {
        if (self.viewType == SearchMoreTagsVCTypeCategory || self.viewType == SearchMoreTagsVCTypeCategoryAndDiscount) {
            static NSString *cellIdentifier = @"LeftCategoryCell";
            RCSearchMoreCategoryCell *cell = (RCSearchMoreCategoryCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (nil == cell) {
                cell = [[[RCSearchMoreCategoryCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]autorelease];
            }
            
            NSInteger row = [indexPath row];
            BOOL isSelect = self.currentSelectedCell == row ? YES:NO;
            NSString *key = nil;
            if (self.dataModel.itemKeyArray != nil) {
                key = [self.dataModel.itemKeyArray safeObjectAtIndex:row];
            }
            [cell setContentViewWithData:key isSelectedf:isSelect];
            return cell;
        }else{
            static NSString *cellIdentifier = @"LeftDistrictCell";
            RCSearchMoreDistrictCell *cell = (RCSearchMoreDistrictCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (nil == cell) {
                cell = [[[RCSearchMoreDistrictCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]autorelease];
            }
            
            NSInteger row = [indexPath row];
            BOOL isSelect = self.currentSelectedCell == row ? YES:NO;
            NSString *key = nil;
            if (self.dataModel.itemKeyArray != nil) {
                key = [self.dataModel.itemKeyArray safeObjectAtIndex:row];
            }
            [cell setContentViewWithData:key isSelectedf:isSelect];
            return cell;
        }
    }else{
        static NSString *cellIdentifier = @"RightCellIdentifier";
        RCSearchRightCell *cell = (RCSearchRightCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (nil == cell) {
            cell = [[[RCSearchRightCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]autorelease];
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
        }
        
        NSInteger row = [indexPath row];
        RCSearchAllCityItem *value = nil;
        value = [self.selectItemArray safeObjectAtIndex:row];
        [cell setContentViewWithData:value];
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (tableView.tag == kLeftTableTag) {
        NSInteger row = [indexPath row];
        self.currentSelectedCell = row;
        NSArray *valueArray = [self.dataModel.itemValueArray safeObjectAtIndex:self.currentSelectedCell];
        if (valueArray != nil) {
            [_selectItemArray removeAllObjects];
            [_selectItemArray addObjectsFromArray:valueArray];
        }
        [_leftTableView reloadData];
        [_rightTableView reloadData];
    }else{
        NSInteger row = [indexPath row];
        RCSearchAllCityItem *value = nil;
        value = [self.selectItemArray safeObjectAtIndex:row];
        if (nil == value || [NSString stringIsNullOrEmpty:value.itemID]) {
            return;
        }
        
        RCMerchantListVC *vc = nil;
        
        if (_viewType == SearchMoreTagsVCTypeCategory) {
            vc =[[RCMerchantListVC alloc] initWithMerchantType:value.itemName withMerchantID:value.itemID];
            vc.vcType = KMerchantListType_Distance;
       
        }else if ( _viewType == SearchMoreTagsVCTypeCategoryAndDiscount) {
            
//            vc =[[RCNearbyDiscountVC alloc] initWithDiscountType:value.itemName withDiscountID:value.itemID];
//            vc.vcType = KMerchantListType_Discount;
            
        }else if ( _viewType == SearchMoreTagsVCTypeAddMerchant) {
            if (_delegate && [_delegate respondsToSelector:@selector(categoryDidSelect:)]) {
                [_delegate categoryDidSelect:value.itemName];
                [self.navigationController popViewControllerAnimated:YES];
                return;
            }
        }else{
            vc =[[RCMerchantListVC alloc] initWithDistrictType:value.itemName withDistrictID:value.itemID];
            vc.vcType = KMerchantListType_District;
        }
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        [vc release];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
